﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ERP.WebUI
{
    public class ModuleRepository 
    {
        private EFDbContext db = new EFDbContext();
        public IQueryable<Module> Modules
        {
            get { return db.Modules; }
        }

        public OperationResult Insert(ModuleModel model)
        {
            var entity = new Module
            {
                Name = model.Name,
                Code = model.Code,
                ParentId = model.ParentId != 0 ? model.ParentId : null,
                LinkUrl = model.LinkUrl,
                Area = model.Area,
                Controller = model.Controller,
                Action = model.Action,
                OrderSort = model.OrderSort,
                Icon = model.Icon != null ? model.Icon : "",
                IsMenu = model.IsMenu,
                Enabled = model.Enabled,
                CreateId = model.CreateId,
                CreateBy = model.CreateBy,
                CreateTime = DateTime.Now
            };
            db.Entry<Module>(entity).State = EntityState.Added;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "添加成功");
        }

        public OperationResult Update(ModuleModel model)
        {
            var entity = new Module
            {
                Id = model.Id,
                Name = model.Name,
                Code = model.Code,
                ParentId = model.ParentId != 0 ? model.ParentId : null,
                LinkUrl = model.LinkUrl,
                Area = model.Area,
                Controller = model.Controller,
                Action = model.Action,
                OrderSort = model.OrderSort,
                Icon = model.Icon != null ? model.Icon : "",
                IsMenu = model.IsMenu,
                Enabled = model.Enabled,
                ModifyId = model.ModifyId,
                ModifyBy = model.ModifyBy,
                ModifyTime = DateTime.Now
            };
            db.Set<Module>().Attach(entity);
            db.Entry<Module>(entity).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "更新成功");
        }

        public OperationResult Delete(int Id)
        {
            var model = Modules.FirstOrDefault(t => t.Id == Id);
            model.IsDeleted = true;

            db.Set<Module>().Attach(model);
            db.Entry<Module>(model).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "删除成功");
        }
    }
}